﻿using FastCloud.Base;
using FastCloud.Base.Attribute;
using FastCloud.Base.Config;
using FastCloud.ORG.DB;
using FastCloud.ORG.Entity;
using FastIOC.Attribute;
using FastORM.Entity;
using FastUtil.Config;
using FastUtil.Convert;
using FastUtil.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FastCloud.Base.Enum.ORG;
using static FastCloud.Base.Result;

namespace FastCloud.Controllers.ORG
{
    [Route("frame/home")]
    public class HomeController : BaseController
    {

        [AutoWired]
        private DB_Login DB_Login;
        [AutoWired]
        private DB_User DB_User;
        [AutoWired]
        private DB_OU DB_OU;
        [AutoWired]
        private TokenUtil TokenUtil;
        [AutoWired]
        private DB_UserJob DB_UserJob;
        [AutoWired]
        private DB_UserJobSetting DB_UserJobSetting;

        [Route("index")]
        public IActionResult Index()
        {
            ViewData["SystemName"] = AppConfigUtil.Configuration["Frame:SystemName"];
            ViewData["DisplayName"] = @TokenUtil.GetTokenEntity().DisplayName;
            ViewData["UserGuid"] = @TokenUtil.GetTokenEntity().UserGuid;
            ViewData["RealUserGuid"] = @TokenUtil.GetTokenEntity().RealUserGuid;
            ViewData["ChangeUserJobUrl"] = AppConfigUtil.Configuration["Frame:ChangeUserJobUrl"];
            ViewData["ExistUserJob"] = DB_UserJob.CheckExistUserJob(@TokenUtil.GetTokenEntity().RealUserGuid);
            return View("~/Views/Home/Home.cshtml");
        }

        [Route("main")]
        public IActionResult Main()
        {
            return View("~/Views/Home/Main.cshtml");
        }

        [Route("login")]
        public IActionResult Login()
        {
            bool OpenVerifyCode = CloudUtil.CheckOpenVerifyCode();
            ViewData["OpenVerifyCode"] = OpenVerifyCode;
            if (OpenVerifyCode)
            {
                string VerifyCode = CloudUtil.CreateRandomCode(4);
                CloudContext.Current.Session.Set("VerifyCode", Encoding.UTF8.GetBytes(VerifyCode));
                ViewData["VerifyCode"] = VerifyCode;
            }
            var Key = EncryptUtil.CreateKey_PEM_PKCS1();
            CloudContext.Current.Session.Set("RSAPrivateKey", Encoding.UTF8.GetBytes(Key[0]));
            ViewBag.RSAPublicKey = Key[1];
            return View("~/Views/Home/Login.cshtml");
        }

        [Route("refreshhVerifyCode")]
        public IActionResult RefreshhVerifyCode()
        {
            string VerifyCode = CloudUtil.CreateRandomCode(4);
            CloudContext.Current.Session.Set("VerifyCode", Encoding.UTF8.GetBytes(VerifyCode));
            return Result.OK(VerifyCode);
        }

        [RequestLog]
        [Route("userlogin"), HttpPost]
        public IActionResult UserLogin()
        {
            string LoginID = ValueConvert.ConvertToString(GetFormParam("LoginID"));
            string Password = ValueConvert.ConvertToString(GetFormParam("Password"));
            string VerfiyCode = ValueConvert.ConvertToString(GetFormParam("VerfiyCode"));
            List<ParamEntity> ParamList = new List<ParamEntity>() { new ParamEntity() { ParamName = "LoginID", ParamValue = LoginID } };
            Frame_Login LoginEntity = DB_Login.SelectOne("*", "LoginID=@LoginID", ParamList);
            if (string.IsNullOrEmpty(LoginID) || string.IsNullOrEmpty(Password))
            {
                return Result.Error("请输入用户名密码！");
            }
            if (CloudUtil.CheckOpenVerifyCode())
            {
                if (string.IsNullOrEmpty(VerfiyCode))
                {
                    return Result.Error("请输入验证码！");
                }
                string SessionVerfiyCode = CloudContext.Current.Session.GetString("VerifyCode");
                if (SessionVerfiyCode != VerfiyCode)
                {
                    return Result.Error("验证码错误！");
                }
            }
            string RSAPrivateKey = CloudContext.Current.Session.GetString("RSAPrivateKey");
            Password = EncryptUtil.RSADecrypt(Password, RSAPrivateKey, "PEM");
            if (LoginEntity != null)
            {
                if (LoginEntity.Enable == (int)FastCloud.Base.Enum.Common.EnableOrDisable.启用 && LoginEntity.AllowManage == (int)FastCloud.Base.Enum.Common.EnableOrDisable.启用)
                {
                    string MD5Password = EncryptUtil.MD5Encrypt(LoginID + "|" + Password);
                    if (LoginEntity.Password == MD5Password)
                    {
                        Frame_User UserEntity = DB_User.SelectOne(LoginEntity.UserGuid);
                        Frame_OU OUEntity = DB_OU.SelectOne(UserEntity.OUGuid);
                        bool ExistUserJob = DB_UserJob.CheckExistUserJob(UserEntity.UserGuid);
                        bool ExistUserJobSetting = DB_UserJobSetting.CheckExistUserJobSetting(UserEntity.UserGuid);
                        if (ExistUserJobSetting)
                        {
                            //对应不同类型兼职进行身份认证切换
                            Frame_UserJob_Setting Setting = DB_UserJobSetting.SelectOneByUserGuid(UserEntity.UserGuid);
                            if (Setting.DefaultUserJobGuid != "UserCommonLogin")
                            {
                                //非普通身份登陆
                                Frame_UserJob Job = DB_UserJob.SelectOne(Setting.DefaultUserJobGuid);
                                if (Job.JobType == (int)JobType.人员兼职)
                                {
                                    UserEntity = DB_User.SelectOne(Job.UserJobGuid);
                                    OUEntity = DB_OU.SelectOne(UserEntity.OUGuid);
                                }
                                else if (Job.JobType == (int)JobType.部门兼职)
                                {
                                    OUEntity = DB_OU.SelectOne(Job.UserJobGuid);
                                }
                            }

                        }
                        string Token = TokenUtil.CreateToken(LoginEntity.UserGuid, UserEntity.UserGuid, UserEntity.LoginID, UserEntity.DisplayName, UserEntity.Mobile,
                            OUEntity.OUGuid, OUEntity.OUName, OUEntity.OUCode, OUEntity.ParentOUGuid);
                        Hashtable result = new Hashtable();
                        result.Add("UserGuid", UserEntity.UserGuid);
                        result.Add("ExistUserJob", ExistUserJob);
                        result.Add("ExistUserJobSetting", ExistUserJobSetting);
                        result.Add("Token", Token);
                        result.Add("RedirectUrl", CloudUtil.GetRootPath() + AppConfigUtil.Configuration["Frame:LoginRedirectUrl"]);
                        result.Add("ChangeUserJobUrl", CloudUtil.GetRootPath() + AppConfigUtil.Configuration["Frame:ChangeUserJobUrl"]);
                        return Result.OK(result);
                    }
                    else
                    {
                        return Result.Error("密码不正确！");
                    }
                }
                else
                {
                    return Result.Error("用户无权限！");
                }

            }
            else
            {
                return Result.Error("用户不存在！");
            }
        }

        [RequestLog]
        [Route("changeUserJob"), HttpPost]
        public IActionResult ChangeUserJob()
        {
            string UserGuid = ValueConvert.ConvertToString(GetFormParam("UserGuid"));
            string RelationGuid = ValueConvert.ConvertToString(GetFormParam("RelationGuid"));
            string UserJobGuid = ValueConvert.ConvertToString(GetFormParam("UserJobGuid"));
            string SetDeafault = ValueConvert.ConvertToString(GetFormParam("SetDeafault"));
            Frame_User UserEntity = DB_User.SelectOne(UserGuid);
            Frame_OU OUEntity = DB_OU.SelectOne(UserEntity.OUGuid);
            Hashtable result = new Hashtable();
            if (UserJobGuid != "UserCommonLogin")
            {
                //对应不同类型兼职进行身份认证切换
                Frame_UserJob Job = DB_UserJob.SelectOne(RelationGuid);
                if (Job.JobType == (int)JobType.人员兼职)
                {
                    UserEntity = DB_User.SelectOne(Job.UserJobGuid);
                    OUEntity = DB_OU.SelectOne(UserEntity.OUGuid);
                }
                else if (Job.JobType == (int)JobType.部门兼职)
                {
                    OUEntity = DB_OU.SelectOne(Job.UserJobGuid);
                }
                TokenUtil.UpdateToken(UserEntity.UserGuid, UserEntity.LoginID, UserEntity.DisplayName, UserEntity.Mobile,
                    OUEntity.OUGuid, OUEntity.OUName, OUEntity.OUCode, OUEntity.ParentOUGuid);
                if (!DB_UserJobSetting.CheckExistUserJobSetting(UserGuid, RelationGuid))
                {
                    if (SetDeafault == "1")
                    {
                        //设置为默认
                        Frame_UserJob_Setting Setting = new Frame_UserJob_Setting();
                        Setting.UserGuid = UserGuid;
                        Setting.DefaultUserJobGuid = RelationGuid;
                        DB_UserJobSetting.Insert(Setting);
                    }
                }
            }
            else
            {
                if (!DB_UserJobSetting.CheckExistUserJobSetting(UserGuid, UserJobGuid))
                {
                    if (SetDeafault == "1")
                    {
                        //设置为默认
                        Frame_UserJob_Setting Setting = new Frame_UserJob_Setting();
                        Setting.UserGuid = UserGuid;
                        Setting.DefaultUserJobGuid = UserJobGuid;
                        DB_UserJobSetting.Insert(Setting);
                    }
                }
                TokenUtil.UpdateToken(UserEntity.UserGuid, UserEntity.LoginID, UserEntity.DisplayName, UserEntity.Mobile,
                  OUEntity.OUGuid, OUEntity.OUName, OUEntity.OUCode, OUEntity.ParentOUGuid);
            }
            result.Add("RedirectUrl", CloudUtil.GetRootPath() + AppConfigUtil.Configuration["Frame:LoginRedirectUrl"]);
            return Result.OK(result);
        }


        [Route("userlogout"), HttpPost]
        public IActionResult UserLogout()
        {
            @TokenUtil.RemoveToken();
            return Result.OK();
        }

        [Route("tokenerror")]
        public IActionResult TokenError()
        {
            ResultModel returnJson = new ResultModel()
            {
                Code = -999,
                Message = "token失效",
                Data = "token失效",
            };
            return new JsonResult(returnJson);
        }

        [Route("getStaticFileVersion"), HttpPost]
        public IActionResult GetStaticFileVersion()
        {
            return Result.OK(AppConfigUtil.Configuration["Frame:StaticFileVsersion"]); 
        }

    }
}
